/**
 * Created by gongxun on 16/12/11.
 */

var WhmjTableLayer = GameCCSBase.extend({
    mWhmjUILayer : null,
    mWhmjCardLayer : null,
    mWhmjAnimLaiziLayer : null,
    mWhmjReplayLayer : null,
    mwhmjJuEndedEventwhmj : null,

    Panel_host : null,

    Laizi_bg : null,

    Button_jiesan : null,

    Text_config : null,

    //牌桌状态 0录像 1正常打牌
    mPlayerType : null,

    //包房名称
    mGroupName : null,

    //包房id 通过退出牌桌消息获得
    mGroupId : null,

    //规则
    mTableConfig : null,

    //游戏密码
    mTableEnterPwd : null,

    //录像id
    mReplayId : null,

    //记录当前局本地打了几盘了
    mPlayGameCount : null,

    //当前轮到哪个玩家操作
    Image_nowSeat : null,

    //剩余牌数
    mCardsLeftText : null,

    //玩法
    mRoundText : null,

    //房间id
    mRoomId : null,

    //倒计时
    mText_leftTime : null,

    //倒计时时间
    mCurLeftTime : null,

    //
    Image_bgEffect : null,

    ctor : function(){
        this._super();
        this.loadCocostudio("res/ccs/WhmjTable.json");
        mo.whmjTabel = this;

        this.mWhmjAnimLaiziLayer = new WhmjAnimLaiziLayer();
        this.addChild(this.mWhmjAnimLaiziLayer);

        this.mWhmjCardLayer = new WhmjCardLayer();
        this.addChild(this.mWhmjCardLayer);

        this.mWhmjUILayer = new WhmjUILayer();
        this.addChild(this.mWhmjUILayer);

        //录像
        this.mWhmjReplayLayer = new WhmjReplayLayer();
        this.addChild(this.mWhmjReplayLayer);

        mo.gameHelper.fixIosText(this.ccsNode);

        this.loadUI();
    },

    onEnter : function(){
        this._super();
        this.runAction(cc.sequence(cc.delayTime(1), cc.callFunc(function(){
            mo.soundHelper.playMusicGame();
        })));


        mo.eventHelper.add("WhmjForceExitTableResponsewhmjOK", this, function () {
            if (mo.whmjTableStatus.mTableStatus.LeftPlayTimes == mo.whmjTabel.mTableConfig.maxpan){
                mo.showMsgDialogOk("退出牌局成功", function(){
                    this.quitWhmjGame();
                }, this);
            }
        });
    },

    onExit : function () {
        this.unschedule(this.refreshLeftTime);
        mo.eventHelper.remove(this);
        this._super();
    },


    loadUI : function(){
        mo.whmjCardHelper.setCardScaleInfo();

        this.Panel_host = mo.seekWidgetByName(this.ccsNode, "Panel_host");
        this.Panel_host.setVisible(false);

        this.Laizi_bg = mo.seekWidgetByName(this.ccsNode, "Image_laiziBg");
        this.Laizi_bg.setVisible(false);


        this.mCardsLeftText = mo.seekWidgetByName(this.ccsNode, "Text_leftCards");
        this.mRoundText = mo.seekWidgetByName(this.ccsNode, "Text_leftJu");
        this.mRoomId = mo.seekWidgetByName(this.ccsNode, "Text_tableRoomId");

        this.Image_nowSeat = mo.seekWidgetByName(this.ccsNode, "Image_nowSeat");
        this.mText_leftTime = mo.seekWidgetByName(this.ccsNode, "Text_leftTime");

        this.Image_bgEffect = mo.seekWidgetByName(this.ccsNode, "Image_bgEffect");

        this.schedule(this.refreshLeftTime, 1.0);

    },


    //播放录像
    loadReplay : function(rePlaywhmj, replayId){
        this.mPlayerType = 0;
        this.mPlayGameCount = 0;
        this.resetTable();

        //录像的规则
        mo.whmjTabel.setWhmjConfig(rePlaywhmj.Result.CfgJson, "", "");

        //关闭退出投票
        //this.mWhmjUILayer.mWhmjTableCancleJuLayer.resetCancelJu(false);

        //打开录像界面 并且播放
        this.mWhmjReplayLayer.setVisible(true);
        this.mWhmjReplayLayer.setReplayId(replayId);
        this.mWhmjReplayLayer.onStart();

        //隐藏录像时候的ui
        this.mWhmjUILayer.setIsReplay(true);
        this.mRoundText.getParent().setVisible(false);
        this.mRoomId.getParent().setVisible(false);

        this.mReplayId = replayId;
        mo.whmjTableStatus.setReplayMsg(rePlaywhmj);
        mo.whmjTableStatus.playReplay();
    },

    //正常打牌
    loadPlayCard : function(){
        this.mPlayerType = 1;
        this.mPlayGameCount = 0;
        this.resetTable();

        //关闭退出投票 换了统一的探矿
        // this.mWhmjUILayer.mWhmjTableCancleJuLayer.resetCancelJu(false);

        //隐藏录像界面
        this.mWhmjReplayLayer.setVisible(false);

        //隐藏录像时候的ui
        this.mWhmjUILayer.setIsReplay(false);
    },

    //设置游戏规则
    setWhmjConfig : function(CfgJson, tablePassWord, groupName){
        //密码
        if (tablePassWord != null){
            this.mTableEnterPwd = tablePassWord;
            if (mo.gameHelper.developerVersion == "2.0"){
                this.mTableEnterPwd = null;
            }
        }

        if (groupName != null){
            this.mGroupName = groupName;
        }

        //规则
        if (CfgJson == ""){
            //没有规则
            this.mTableConfig = null;
        }else{
            this.mTableConfig = JSON.parse(CfgJson);
        }

        mo.whmjCardHelper.ruleGouhu = 5;
        mo.whmjCardHelper.ruleJinding = 9;


        this.Text_config = mo.seekWidgetByName(this.ccsNode, "Text_config");
        if (this.mTableConfig){
            this.Text_config.setVisible(true);

            var ruleStr = "";

            var wanfa = ["红中发财杠", "赖子皮杠"];
            var openrate = ["开口番", "口口番"];
            var huscore = ["16", "32"];

            ruleStr += wanfa[this.mTableConfig.ruleid - 1] + "，";
            ruleStr += openrate[this.mTableConfig.openrate - 1] + "，";
            ruleStr += "起胡分数：" + huscore[this.mTableConfig.openrate - 1] + "分";

            this.Text_config.setString(ruleStr);
            // mo.gameHelper.setTextString(mo.seekWidgetByName(Panel_ruleInfo, "TextFull_tableRule"), ruleStr);
        }
        else{
            this.Text_config.setVisible(false);
        }

    },


    //发牌动画 加翻赖子
    setInhandCards : function(cardNumss, laizi, singCards){
        //清空牌桌
        this.resetTable();

        //设置赖子
        mo.whmjCardHelper.setLaiziCard(laizi);

        //设置单杠
        mo.whmjCardHelper.setSingCards(singCards);

        //先发牌
        this.mWhmjCardLayer.setInhandCards(cardNumss);

        //然后飞赖子
        var that = this;
        that.mWhmjAnimLaiziLayer.startAnimLaizi(mo.whmjCardHelper.laiziNum);

        //是否原赖翻番
        if(this.mTableConfig.yl == 1){
            if(mo.whmjCardHelper.laiziNum == mo.whmjCardHelper.lastLaiziNum){
                for (var i = 0; i < 4; i++){
                    this.mWhmjCardLayer.mPlayers[i].fanshu += 1;
                    //todo 原赖翻番动画提示
                }
            }
            mo.whmjCardHelper.lastLaiziNum = mo.whmjCardHelper.laiziNum;
            //todo 断线重连后 原赖不知道
        }

        //是否峰赖翻番
        if(this.mTableConfig.fl == 1){
            if(laizi == 81 || laizi == 82 || laizi == 83 || laizi == 84 || laizi == 87){
                for (var i = 0; i < 4; i++){
                    this.mWhmjCardLayer.mPlayers[i].fanshu += 1;
                    //todo 峰赖翻番动画提示
                }
            }
        }

    },

    addInhandCard : function(seat, cardNum){
        this.mWhmjCardLayer.addInhandCard(seat, cardNum);
    },

    setDealCard : function(seat, cardNum){
        this.mWhmjCardLayer.setDealCard(seat, cardNum);
    },

    //重置牌桌
    resetTable : function(){

        this.mWhmjCardLayer.removeAllCard();
        this.mWhmjCardLayer.setLastPointerShow(false);
    },

    updateTableStep : function (step) {
        //准备界面
        this.mWhmjUILayer.showReady(step == 0 && this.mPlayGameCount == 0);

        this.Text_config.setVisible(step == 0);

        //该谁打牌,剩余牌数，房号等
        this.Panel_host.setVisible(step == 1);

        this.Laizi_bg.setVisible(step == 1);

        //控制游戏的结算画面
        if (step == 0){
            var selfSeatUser = mo.whmjTableStatus.mTableStatus["SeatUser" + mo.whmjTableStatus.mTableStatus.MySeat];
            if (selfSeatUser.State == 1){
                this.mWhmjUILayer.mWhmjTableEndLayer.setVisible(false);
            }
        }else{
            this.mWhmjUILayer.mWhmjTableEndLayer.setVisible(false);
        }


        if(step == 1){
            //更新剩余牌数，番数，够胡等
            this.setTableInfo();
        }

        //房间密码
        mo.gameHelper.setTextString(this.mRoomId, mo.whmjTableStatus.mTableStatus.TableID);
    },

    setTableInfo : function () {
        var fanshuNums = [];

        var gouhus = [];

        var jindins = [];

        for(var i=0; i<4; i++){
            var playerModer = mo.whmjTabel.mWhmjCardLayer.mPlayers[i];

            //设置番数
            fanshuNums.push(playerModer.fanshu);

            //设置够胡
            var gouhu = true;
            for (var j = 0; j < 4; j++){
                var otherPlayerModer = mo.whmjTabel.mWhmjCardLayer.mPlayers[j];
                if(i == j){
                    continue;
                }

                //todo 具体够胡番数待确定
                if(playerModer.fanshu + otherPlayerModer.fanshu < 5){
                    gouhu = false;
                    break;
                }
            }
            gouhus.push(gouhu);


            //设置金顶
            var jindin = true;
            for (var j = 0; j < 4; j++){
                var otherPlayerModer = mo.whmjTabel.mWhmjCardLayer.mPlayers[j];
                if(this.mTableConfig.alltop == 0){
                    jindin = false;
                    break;
                }

                if(i == j){
                    continue;
                }

                if(playerModer.fanshu + otherPlayerModer.fanshu < this.mTableConfig.alltop){
                    jindin = false;
                    break;
                }

            }
            jindins.push(jindin);
        }

        //设置番数
        mo.whmjTabel.mWhmjUILayer.setFanshu(fanshuNums);

        //设置够胡
        mo.whmjTabel.mWhmjUILayer.setHostStatus(gouhus, jindins);

        //剩余牌数
        var cardsLeft = mo.whmjTableStatus.mTableStatus.LeftCards;
        mo.gameHelper.setTextString(this.mCardsLeftText, cardsLeft);

        //当前第几局
        var round =  mo.whmjTableStatus.mTableStatus.LeftPlayTimes;
        mo.gameHelper.setTextString(this.mRoundText, round);

    },

    setOpenCard : function(seat, cardNums, openType){
        this.mWhmjCardLayer.setOpenCard(seat, cardNums, openType);

        if(openType == 4 || openType == 5 || openType == 6
            || (openType == 7 && mo.whmjCardHelper.getIsLaizi(cardNums[0]))){
            this.onPlayTableOpAnim();
        }
    },
    // setSingCard : function (seat, cardNum) {
    //     this.mWhmjCardLayer.setSingCard(seat, cardNum);
    //
    //     this.mWhmjUILayer.singCardAction(seat, cardNum);
    // },


    //分享录像


    //openType
    //1 吃 3张
    //2 碰 3张
    //4 明杠 4张
    //5 暗杠 4张
    //6 补杠 1张
    //7 单杠 1张

    //加载大结算
    onShowJuEndedLayer : function(juEndedEventwhmj){
        //判断是否需要直接退出 如果剩余局数和设置里面的局数一致 就直接退出
        var ruleJson = JSON.parse(juEndedEventwhmj.CfgJson);
        //打了多少局
        juEndedEventwhmj.curpan = ruleJson.maxpan - mo.whmjTableStatus.mTableStatus.LeftPlayTimes;

        if (mo.whmjTableStatus.mTableStatus.LeftPlayTimes == ruleJson.maxpan){
            mo.showMsgDialogOk("退出牌局成功", function(){
                this.quitWhmjGame();
            }, this);
        }else{

            this.mwhmjJuEndedEventwhmj = new WhmjTableRoomEndLayer();
            mo.sceneHelper.showEndInfoLayer(this.mwhmjJuEndedEventwhmj);
            // this.addChild(this.mwhmjJuEndedEventwhmj);
            this.mwhmjJuEndedEventwhmj.setRoomEndInfo(juEndedEventwhmj);

            if (juEndedEventwhmj.EndFlag == 0){
                //自然结束 通过当局结算打开
                this.mwhmjJuEndedEventwhmj.setVisible(false);
            }else{
                this.mwhmjJuEndedEventwhmj.setVisible(true);
            }
        }
    },
    onShareReplay : function(){
        var gameName = "whmj";
        var configSummary = mo.gameHelper.getRuleConfigSummary(this.mTableConfig, gameName);
        configSummary += "，在游戏中输入录像id就能看到我的精彩回放了";
        var title = "";
        var description = "";

        if (mo.gameHelper.developerVersion == "3.0"){
            title = "录像id:" + this.mReplayId.substr(7) + "-新蜂-卡五星";
            description = configSummary;
        }else if (mo.gameHelper.developerVersion == "2.0"){
            title = "录像id:" + this.mReplayId.substr(7) + "-新蜂-武汉麻将";
            description = configSummary;
        }

        mo.gameHelper.onWxShareWeb(title, description, mo.gameUserInfo.getExternalUrl(2, this.mReplayId.substr(7)));
    },

    //播放分数动画
    // setResultScore : function(scores){
    //     this.mWhmjUILayer.mWhmjTableResultLayer.setResultScore(scores);
    // },

    //处理货币结算
    onHandlerTableResult : function(){
        mo.whmjTableStatus.handlerTableResult();
    },


    quitWhmjGame : function(){
        if (mo.gameHelper.developerVersion == "2.0"){
            mo.sceneHelper.runSceneHall();
        }else if (mo.gameHelper.developerVersion == "3.0"){
            mo.sceneHelper.exitGameLayer();
            if (this.mGroupId != null){
                mo.hallLayer.intoGroup(this.mGroupId);
            }
        }
    },



    //邀请玩家
    onInvite : function(){
        if (mo.gameHelper.developerVersion == "3.0"){
            var gameName = "whmj";
            var tableId = mo.whmjTableStatus.mTableStatus.TableID;
            var pwd = this.mTableEnterPwd;
            var title = "开局分享-新蜂麻将-武汉麻将";
            var description = "桌号:[" + tableId + "]" + "速度加入！";
            if (this.mTableConfig != null && this.mTableConfig.pwd == 1){
                description = "我在新蜂麻将开了一桌[武汉麻将]" + ",密码:[" + pwd + "]," + "速度加入！";
            }
            mo.gameHelper.onWxShareWeb(title, description, mo.gameUserInfo.getExternalUrl(0, pwd));
        }else if (mo.gameHelper.developerVersion == "2.0"){
            var gameName = "whmj";
            var tableId = mo.whmjTableStatus.mTableStatus.TableID;
            var pwd = "123";
            var title = "桌号:[" + tableId + "]" + "-武汉麻将";
            var description = "我创建了一个武汉麻将牌局，桌号:[" + tableId + "]" + "快来和我一起游戏吧";
            mo.gameHelper.onWxShareWeb(title, description, mo.gameUserInfo.getExternalUrl(1, tableId));
        }
    },


    //设置当前操作玩家
    setCurrentPlayer : function(seat){

        this.Image_nowSeat.stopAllActions();
        this.Image_nowSeat.runAction(cc.rotateTo(0.2,  - 90 * seat));

        this.mCurLeftTime = 15;
        mo.gameHelper.setTextString(this.mText_leftTime, this.mCurLeftTime);
    },

    refreshLeftTime : function () {

        this.mCurLeftTime -= 1;
        if(this.mCurLeftTime < 0){
            this.mCurLeftTime = 0;
        }

        mo.gameHelper.setTextString(this.mText_leftTime, this.mCurLeftTime);
    },

    //播放龙动画
    onPlayTableOpAnim : function(){
        this.Image_bgEffect.stopAllActions();
        this.Image_bgEffect.setVisible(false);
        this.Image_bgEffect.setOpacity(150);
        this.Image_bgEffect.runAction(cc.sequence(
            cc.delayTime(0.55),
            cc.show(),
            cc.fadeOut(1),
            cc.hide()
        ));

        this.runAction(cc.sequence(
            cc.delayTime(0.50),
            cc.moveTo(0.05, cc.p(0, -15)),
            cc.moveTo(0.05, cc.p(0, 0)),
            cc.moveTo(0.03, cc.p(0, -10)),
            cc.moveTo(0.03, cc.p(0, 0))
        ));
    },


});

